#!/usr/bin/env bash

include "libs/database.sh"
include "libs/ohos.sh"
include "libs/output.sh"
include "libs/regex.sh"

#help.cmd repo@status : (仓库) 查看仓库状态(检查 修改已跟踪文件 和 新分支)
#alias.cmd orss : repo@status
dynamic_cmd:repo:status()
{
    database:repo_load || return
    if [ "$(database:repo_get sync_time)" != "0" ]; then
        echo "上次成功同步时间: $(date -d @$(database:repo_get sync_time))"
    fi

    local repo=".repo/repo/repo"
    local result="$($repo forall -c "[ \"\$(git status -s --untracked-files=no)\$(git symbolic-ref --short -q HEAD)\" != \"\" ] && pwd")"
    if [ "$result" = "" ]; then
        report "干净的仓库"
        return 0
    fi
    local max=$(echo "$result" | while read str; do
        echo ${str:((${#REPO_PATH}+1))} | wc -c
    done | sort -k 1 | tail -1)
    ((max+=9))

    echo "$result" | while read str; do
        local repo=${str:((${#REPO_PATH}+1))}
        cd $repo
        if [ "$(git symbolic-ref --short -q HEAD)" != "" ]; then
            printf "%-${max}s %s\n" "$(cctl c)${repo}$(cctl 0)" "$(cctl g)起了新分支: $(git symbolic-ref --short -q HEAD)$(cctl 0)"
        fi
        cd - 1>/dev/null
    done

    echo "$result" | while read str; do
        local repo=${str:((${#REPO_PATH}+1))}
        cd $repo
        if [ "$(git status -s --untracked-files=no)" != "" ]; then
            printf "%-${max}s %s\n" "$(cctl c)${repo}$(cctl 0)" "$(cctl y)$(git status -s | wc -l) $(cctl r)项未提交修改$(cctl 0)"
        fi
        cd - 1>/dev/null
    done
}

#help.cmd repo@sync : (仓库) 同步代码
#alias.cmd ors : repo@sync
dynamic_cmd:repo:sync()
{
    ohos:cd_repo || return
    database:repo_load || return
    if [ "$(git config --global advice.detachedHead)" = "true" ]; then
        git config --global advice.detachedHead false
    fi
    local repo=".repo/repo/repo"

    if [ "$(database:repo_get sync_time)" != "0" ]; then
        local sync_time="$(database:repo_get sync_time)"
        sync_time="$(date -d @$sync_time)"
        output:logi "上次成功同步时间: $sync_time"
    fi

    # $repo forall -c "pwd; \
    #     git reset; \
    #     git clean -dfx; \
    #     git checkout -- .; \
    #     git checkout $MAIN_BRANCH 1>/dev/null 2>&1"

    args=(-j8)
    args+=(--force-sync)
    if [ ! -e .repo/repo/.git/clone.bundle ]; then
        args+=(--no-clone-bundle)
    fi

    output:logi "repo syncing"
    if $repo sync ${args[*]}; then
        output:logi "repo sync success"
    else
        output:logi "repo sync failed"
        return 1
    fi

    output:logi "repo pulling lfs(large filesystem)"
    cmds='echo -en "\033[2K[$REPO_I/$REPO_COUNT] $REPO_PATH \033[spulling";'
    cmds+='if git lfs pull; then'
    cmds+='    echo -e "\033[u\033[1A";'
    cmds+='else'
    cmds+='    echo -e "\033[ufailed!";'
    cmds+='    exit 1;'
    cmds+='fi'
    if $repo forall -c "$cmds"; then
        output:logi "repo pull lfs success"
    else
        output:logi "repo pull lfs failed"
        return 1
    fi

    # $repo forall -c "git checkout $MAIN_BRANCH 1>/dev/null 2>&1 || echo error in: $(pwd)"

    output:logi "recording success sync"
    if ! database:repo_load; then
        output:loge "record failed, database:repo_load failed"
        return 1
    fi

    database:repo_set sync_time "$(date +%s)"
    if ! database:repo_save; then
        output:loge "record failed, database:repo_save failed"
        return 1
    fi

    output:logi "record success"

    message_box
}

#help.cmd repo@date : (仓库) 查看当前仓库最近一笔提交的时间
dynamic_cmd:repo:date()
{
    ohos:cd_repo || return
    local repo=".repo/repo/repo"
    local dates="$($repo forall -c "git branch --format '%(committerdate) %(refname:short)' -a" | grep " m/master")"
    dates="$(awk '{$NF=""; $(NF-1)=""; print}' <<< "$dates")"
    dates="$(while read line; do date +%s -d "$line"; done <<< "$dates")"
    dates="$(sort <<< "$dates")"
    dates="$(tail -1 <<< "$dates")"
    date -d @"$dates"
}

#help.cmd repo@back YYYY-MM-DD [hh:mm] : (仓库) 将所有仓库都赶回某个时间之前
dynamic_cmd:repo:back()
{
    ohos:cd_repo || return
    local time=""
    if (( $# >= 1 )); then
        if ! [[ "$1" =~ ($regex_date) ]]; then
            echo "$1 isn't like YYYY-MM-DD"
            return 1
        else
            time="$1"
        fi
    else
        echo "需要至少一个参数"
        return 1
    fi

    if (( $# >= 2 )); then
        if ! [[ "$2" =~ ($regex_time) ]]; then
            echo "$1 isn't like hh:mm"
            return 1
        else
            time="$time $2"
        fi
    fi

    repo forall -c "git reset --hard \$(git log --before \"$time\" -1 --format=%H)"
}

#help.cmd repo@init : (仓库) 初始化一个master仓库
#alias.cmd ori : repo@init
dynamic_cmd:repo:init()
{
    ohos:cd_repo || return
    if [ -d .repo ]; then
        output:loge "已存在仓库，无需初始化"
        return 1
    fi

    output:logd "downloading repo"
    if curl -s https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > repo.py; then
        output:logi "download repo success"
    else
        output:loge "download repo failed"
        return 1
    fi

    output:logd "repo initing"
    if python repo.py init -u https://gitee.com/openharmony/manifest.git -b master; then
        output:logi "repo init success"
    else
        output:loge "repo init failed"
        return 1
    fi

    rm repo.py

    dynamic_cmd:repo:sync || return

    output:logd "downloading prebuilts"
    if bash ./build/prebuilts_download.sh; then
        output:logi "download prebuilts success"
    else
        output:loge "download prebuilts failed"
        return 1
    fi
}
